package com.atguigu.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {


    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;


        OSS ossClient = null;
        try {
            // 创建 OSS 实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();

            // 获取文件名称
            String fileName = file.getOriginalFilename();

            // 随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            // 1、防止相同文件名覆盖xxxx01.jpg
            fileName = uuid + fileName;

            // 2、把文件按照日期进行分类
            String date = new DateTime().toString("yyyy/MM/dd");

            // 拼接
            fileName = date + "/" + fileName;

            /**
             * 调用 OSS 文件实现上传
             * 第一个参数 Bucket 名称
             * 第二个参数 上传到 oss文件路径和文件名称  /aa/bb/1.jpg
             * 第三个参数 上传文件输入流
             */
            ossClient.putObject(bucketName, fileName, inputStream);

            String url = "http://" + bucketName + "." + endpoint + "/" + fileName;

            return url;
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

        return "";
    }
}
